package game;

import static game.Settings.loadTradeMarketResources;
import static utils.StrategyGameUtils.getResourceWithType;

import java.util.List;

import exceptions.CanNotTradeException;

public class MarketPlace {

	private List<Resource> resources = null;
	private volatile boolean canTrade = false;
	private static MarketPlace instance = null;

	public static MarketPlace getInstance() {
		synchronized (MarketPlace.class) {
			if (instance == null) {
				instance = new MarketPlace();
			}
			return instance;
		}
	}

	private MarketPlace() {
		resources = loadTradeMarketResources();
		canTrade = true;
	}

	public synchronized Resource exchange(Types needed, int qneeded,
			Types traded, int qtraded) throws CanNotTradeException, InterruptedException {
		while (!canTrade) {
				wait();
		}
		canTrade = false;
		boolean found = false;
		Resource neededResource = new Resource(needed, qneeded);
		Resource tradedResource = new Resource(traded, qtraded);
		for (Resource i : resources) {
			if (i.equals(neededResource)) {
				found = true;
				if (i.getCurrentQuantity() == 0)
					throw new CanNotTradeException(" there aren't " + qneeded
							+ " pieces of " + needed + " in the MarketPlace");
				if (i.getCurrentQuantity() >= qneeded) {
					i.decrease(qneeded);
				} else {
					neededResource = new Resource(needed,
							i.getCurrentQuantity());
					i.decrease(i.getCurrentQuantity());
				}
			}
		}
		if (found) {
			Resource i = getResourceWithType(resources, traded);
			if (i != null) {
				i.increase(qtraded);
			} else {
				resources.add(tradedResource);
			}
			notifyAll();
			canTrade = true;
		} else {
			notifyAll();
			canTrade = true;
			throw new CanNotTradeException(" there aren't " + qneeded
					+ " pieces of " + needed + " in the MarketPlace");
		}
		return neededResource;
	}
}